package com.qf.lja.servlet;

import com.qf.lja.dao.ProductDao;
import com.qf.lja.enity.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebServlet(urlPatterns = "/performSearch")
public class ProductLikeServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //
        String search = req.getParameter("searchText");

        ProductDao productDao = new ProductDao();
        List<Product> products = productDao.findLike(search);


        //分页
        String pageSize = req.getParameter("pageSize");
        String currentPage = req.getParameter("currentPage");
        int pageSizeInt = 8;
        if (pageSize != null && !"".equals(pageSize)) {
            pageSizeInt = Integer.parseInt(pageSize);
            if (pageSizeInt < 1 || pageSizeInt > 100) {
                pageSizeInt = 10;   // 超出页面范围就设置默认值
            }
        }

        int currentPageInt = 1; // 当前页数
        int rows = products.size(); // 获取产品总数
        int totalPage = (int) Math.ceil(1.0 * rows / pageSizeInt); // 计算总页数
        if (currentPage != null && !"".equals(currentPage)) {
            currentPageInt = Integer.parseInt(currentPage);
            if (currentPageInt < 1 || currentPageInt > totalPage) {
                currentPageInt = 1; // 当前页超出范围，使用默认值
            }
        }


        // 将产品列表存储到请求属性中

        req.setAttribute("pageSize", pageSizeInt);
        req.setAttribute("totalPage", totalPage);
        req.setAttribute("currentPage", currentPageInt);


        System.out.println("size : " + products.size());
        req.setAttribute("productList", products);
        req.getRequestDispatcher("/goodsList.jsp").forward(req, resp);
    }
}
